# !/user/bin/env python3
# -*- encoding: utf-8 -*-
'''
@File    :   download_notary_paper.py
@Time    :   2020/09/23 19:41:16
@Author  :   cecil-y 
@Version :   1.0
@Desc    :   None

下载公证书

'''

# here put the import lib
from base64 import b64encode, encodebytes
from Crypto.Cipher import AES
import binascii
import hashlib
import requests
import os

BS = AES.block_size


def padding_pkcs5(value):
    return str.encode(value + (BS - len(value.encode('utf-8')) % BS) *
                      chr(BS - len(value.encode('utf-8')) % BS))


def padding_zero(value):
    while len(value) % 16 != 0:
        value += '\0'
    return str.encode(value)


def aes_ecb_encrypt(key, value):
    ''' AES/ECB/NoPadding encrypt '''
    key = bytes.fromhex(key)
    cryptor = AES.new(key, AES.MODE_ECB)
    ciphertext = cryptor.encrypt(bytes.fromhex(value))
    return ''.join(['%02x' % i for i in ciphertext]).upper()


def aes_ecb_decrypt(key: str, value: str) -> str:
    ''' AES/ECB/NoPadding decrypt '''
    key = bytes.fromhex(key)
    cryptor = AES.new(key, AES.MODE_ECB)
    ciphertext = cryptor.decrypt(bytes.fromhex(value))
    return ''.join(['%02x' % i for i in ciphertext]).upper()


def get_userkey(key, value):
    ''' AES/ECB/PKCS5Padding encrypt 
    就是一个普通的AES ECB加密，填充方式是PKCS5Padding 
    '''
    cryptor = AES.new(bytes.fromhex(key), AES.MODE_ECB)
    padding_value = padding_pkcs5(value)
    ciphertext = cryptor.encrypt(padding_value)
    return ''.join(['%02x' % i for i in ciphertext]).upper()


def get_sha1prng_key(key):
    '''[summary]
    encrypt key with SHA1PRNG
    same as java AES crypto key generator SHA1PRNG
    Arguments:
        key {[string]} -- [key]
    
    Returns:
        [string] -- [hexstring]
    '''
    signature = hashlib.sha1(key.encode()).digest()
    signature = hashlib.sha1(signature).digest()
    return ''.join(['%02x' % i for i in signature]).upper()[:32]


def download(filename, order_num, encrypted_data):
    session = requests.session()
    session.headers.update({
        "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0"
    })
    url = "https://www.ezcun.com/eviddeposit/searchNotaryPaper/pdu/" + order_num + "/" + encrypted_data
    print("url:", url)
    r = session.get(url=url)
    if (r.status_code == 200):
        with open(filename + ".pdf", 'wb') as f:
            f.write(r.content)
        os.startfile(filename + '.pdf')
    else:
        print("下载失败：", r.text)

# 解密
def decrypt(key, value):
    cryptor = AES.new(bytes.fromhex(key), AES.MODE_ECB)
    ciphertext = cryptor.decrypt(bytes.fromhex(value))
    return str(ciphertext, "utf-8")

# # 普通AES ECB加解密
# data = '0513011E0005016400000000000000000001000000000000000000000000000000770013011E0005026400000000000000000001000000000000000000000000000000770013011E0005036400000000000000000001000000000000000000000000000000770013011E0005046400000000000000000001000000000000000000000000000000770013011E000505640000000000000000000100000000000000000000000000000077000000000000'   # 原文
# key = '43C8B53E236C4756B8FF24E5AA08A549'   #加密key
# aes_result = 'AB4F4686218A5FF9F07E5248E6B5525D140602A0FAA21176C9A158A010B1A7C0258E80667BF7DD3B6FF57707B373BF75F57AE634D9F1384002AA6B788F4C658DD77572C207AAE3134F91FB690A4F024EF428DE3E1C5F84D0EA9D01B8AB4ED9FE97D7C0D65D447D92F0E306573F30E1360B3DE999E952BAAB9B22E48B8C7B23DC5480027DEE44988F0E86F7A475EEF599C1D7D3331457E582558BC3447E644913ABD63FC221C2E0D49BD712879261FF5F'   #加密结果
# # 加密
# aes128string = aes_ecb_encrypt(key, data)
# print(aes128string)
# # 解密
# aes128string = aes_ecb_decrypt(key, aes_result)
# print(aes128string)

# # sha1prng 加密方式
# mac = '405EE11002F3'   #原文
# device_id = '12532802' #'12403492' #'12532802'  # 加密key
# user_key = 'c1ee1f3f2d74e02706be9af78aa79ba4'.upper()  # 加密结果

# # 加密
# # 1.对key 进行sha1prng加密， 就是方法get_sha1prng_key
# # 2.用加密后的key进行AES AES/ECB/PKCS5Padding 加密，
# # 注意看你的java代码AES加密方式，填充方式，我这里是ECB加密，填充方式是PKCS5Padding
# # get_userkey 方法就是普通的 AES/ECB/PKCS5Padding 加密
# # https://blog.csdn.net/max229max/article/details/70318782  这篇有AES的ECB和CBC加密
# aes128string = get_userkey(get_sha1prng_key(device_id), mac)
# print(aes128string)

# # 58F7CD929BFAA0915032536FBA8D3281420E93E3
# # 58f7cd929bfaa0915032536fba8d3281
# # 58F7CD929BFAA0915032536FBA8D3281
# print(get_sha1prng_key('12532802')) # 58f7cd929bfaa0915032536fba8d3281

if __name__ == '__main__':

    orderNum = input("请输入申办订单号：")
    notarialNum = input("请输入完整的公证书编号：")

    key = get_sha1prng_key(orderNum)
    encrypted_data = get_userkey(key, notarialNum)
    print("encrypted_data:", encrypted_data)

    data = decrypt(key, encrypted_data)
    print("data:", data)

    # download(notarialNum, orderNum, encrypted_data)
    pass